package cn.lblbc.webbrowser

import android.app.Activity
import android.app.Application
import android.content.Context
import android.content.Intent
import android.graphics.BitmapFactory
import android.os.Bundle
import android.util.Log
import cn.lblbc.webbrowser.CalculatorActivity
import cn.lblbc.webbrowser.utils.CompletedDownloadManager
import cn.lblbc.webbrowser.utils.CustomDownloader
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.io.File
import java.io.FileOutputStream

/**
 * 浏览器应用全局Application类
 * 用于提供全局访问的下载管理器实例
 */
class BrowserApplication : Application(), Application.ActivityLifecycleCallbacks {
    // 全局的自定义下载器实例
    lateinit var customDownloader: CustomDownloader
        private set

    // 全局的已完成下载管理器实例
    lateinit var completedDownloadManager: CompletedDownloadManager
        private set

    private var numStarted = 0
    private var appInBackground = false // On first launch, don't show calculator.

    companion object {
        private const val TAG = "BrowserApplication"
    }

    override fun onCreate() {
        super.onCreate()
        registerActivityLifecycleCallbacks(this)

        // 初始化下载相关组件
        customDownloader = CustomDownloader(this)
        completedDownloadManager = CompletedDownloadManager(this)

        // 首次启动时复制 drawable 中的 img 开头资源到外部目录
        copyBundledImagesOnFirstLaunch()
    }
    
    /**
     * 首次启动时将 drawable 中以 img 开头的资源复制到外部图片目录
     */
    private fun copyBundledImagesOnFirstLaunch() {
        val prefs = getSharedPreferences("image_collector_prefs", Context.MODE_PRIVATE)
        if (prefs.getBoolean("bundled_images_copied", false)) return

        CoroutineScope(Dispatchers.IO).launch {
            try {
                val imageDirectory = File(getExternalFilesDir(null), "Pictures/WebImages").apply {
                    if (!exists()) {
                        mkdirs()
                    }
                }
                
                val pkg = packageName
                val drawableClass = try {
                    Class.forName("$pkg.R\$drawable")
                } catch (e: Exception) {
                    e.printStackTrace()
                    null
                }

                if (drawableClass == null) {
                    prefs.edit().putBoolean("bundled_images_copied", true).apply()
                    return@launch
                }

                val fields = drawableClass.declaredFields
                for (field in fields) {
                    val name = field.name
                    if (!name.startsWith("img")) continue

                    val resId = try {
                        field.getInt(null)
                    } catch (e: Exception) {
                        continue
                    }

                    val outFile = File(imageDirectory, "$name.png")
                    if (outFile.exists()) continue

                    try {
                        resources.openRawResource(resId).use { input ->
                            val bytes = input.readBytes()
                            val bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.size)
                            if (bitmap != null) {
                                FileOutputStream(outFile).use { fos ->
                                    bitmap.compress(android.graphics.Bitmap.CompressFormat.PNG, 100, fos)
                                }
                            } else {
                                FileOutputStream(outFile).use { fos ->
                                    fos.write(bytes)
                                }
                            }
                        }
                    } catch (e: Exception) {
                        e.printStackTrace()
                    }
                }

                prefs.edit().putBoolean("bundled_images_copied", true).apply()
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }

    override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {
        Log.d(TAG, "onActivityCreated: ${activity.javaClass.simpleName}")
    }

    override fun onActivityStarted(activity: Activity) {
        Log.d(TAG, "onActivityStarted: ${activity.javaClass.simpleName}, numStarted before: $numStarted")
        if (numStarted == 0) {
            // App is coming to foreground
            Log.d(TAG, "App is coming to foreground. appInBackground: $appInBackground")
            if (appInBackground) {
                if (activity !is CalculatorActivity) {
                    Log.d(TAG, "Showing CalculatorActivity on top of ${activity.javaClass.simpleName}")
                    val intent = Intent(activity, CalculatorActivity::class.java)
                    intent.putExtra("IS_PASSWORD_GATE", true)
                    activity.startActivity(intent)
                } else {
                    Log.d(TAG, "Already in CalculatorActivity, not showing another one.")
                }
            }
        }
        numStarted++
        Log.d(TAG, "onActivityStarted: ${activity.javaClass.simpleName}, numStarted after: $numStarted")
    }

    override fun onActivityResumed(activity: Activity) {
        Log.d(TAG, "onActivityResumed: ${activity.javaClass.simpleName}")
    }

    override fun onActivityPaused(activity: Activity) {
        Log.d(TAG, "onActivityPaused: ${activity.javaClass.simpleName}")
    }

    override fun onActivityStopped(activity: Activity) {
        numStarted--
        Log.d(TAG, "onActivityStopped: ${activity.javaClass.simpleName}, numStarted after: $numStarted")
        if (numStarted == 0) {
            // App is going to background
            Log.d(TAG, "App is going to background.")
            appInBackground = true
        }
    }

    override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {
        Log.d(TAG, "onActivitySaveInstanceState: ${activity.javaClass.simpleName}")
    }

    override fun onActivityDestroyed(activity: Activity) {
        Log.d(TAG, "onActivityDestroyed: ${activity.javaClass.simpleName}")
    }
}